package nb.diskfilesystem.controller;

import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.TilePane;
import nb.diskfilesystem.*;

import java.util.List;
import java.util.Stack;

public class MainController {
    @FXML
    private BorderPane root;

    @FXML
    private TilePane fileArea;

    @FXML
    private BorderPane blockVIew;

    @FXML
    private BorderPane circleView;

    @FXML
    private Button fresh;

    @FXML
    private Button lastFile;

    @FXML
    private Button advanceFile;

    @FXML
    private Button backFile;

    @FXML
    private TextField searchfield;

    @FXML
    private TreeView<String> directoryTreeView; // 添加 TreeView 控件

    @FXML
    private TableView<FAT_tableEntry> FAT_table; // 添加 TableView 控件


    public static Stack<String> backStack = new Stack<>();
    public static Stack<String> forwardStack = new Stack<>();

    public static BorderPane rootNode;
    private FileContextMenu fileContextMenu;

    @FXML
    private void initialize() {
        MainController.rootNode = root;
        fileContextMenu= new FileContextMenu(directoryTreeView);
        System.out.println("默认先运行这里");
        DiskManage.start(); // 启动加载方法
        DiskManage.diskPrint();
        initTreeView();
        addTreeViewListener();

        // 初始化显示C盘内容
        initRootContent();

        // 初始化 FAT 表管理器
        FATManage.initFATTable(FAT_table);

        // 初始化磁盘使用情况显示
        DiskVisualization.updateViews(blockVIew, circleView);

        // 将场景监听器设置提取到单独的方法中
        setupSceneListener();

        searchfield.setOnAction(event -> handleSearch());

        fresh.setOnAction(event -> handleFresh());
        lastFile.setOnAction(event -> handleLastFile());
        backFile.setOnAction(event -> handleBackFile());
        advanceFile.setOnAction(event -> handleAdvanceFile());

        // 加载TreeView样式
        directoryTreeView.getStylesheets().add(
                getClass().getResource("/nb/diskfilesystem/css/treeview.css").toExternalForm()
        );

    }

    @FXML
    private void handleSearch() {
        System.out.println("handleSearch被调用");
        TextField searchField = (TextField) rootNode.lookup("#searchfield");
        if (searchField != null) {
            String keyword = searchField.getText();
            ViewHandler viewHandler = new ViewHandler(directoryTreeView, fileArea, fileContextMenu);
            viewHandler.searchFiles(keyword);
        }
    }

    private void initTreeView() {
        DirectoryTreeBuilder treeBuilder = new DirectoryTreeBuilder();
        TreeItem<String> cDrive = treeBuilder.buildDirectoryTree();
        directoryTreeView.setRoot(cDrive);
        directoryTreeView.setShowRoot(true);

        // 添加样式类
        directoryTreeView.getStyleClass().add("custom-tree-view");

        // 设置单元格工厂来自定义每个项的显示
        directoryTreeView.setCellFactory(tv -> new TreeCell<String>() {
            private ImageView folderIcon;

            {
                // 初始化文件夹图标
                try {
                    Image folderImage = new Image("file:src/main/resources/nb/diskfilesystem/img/目录文件夹.png");
                    folderIcon = new ImageView(folderImage);
                    folderIcon.setFitWidth(14);  // 设置图标大小
                    folderIcon.setFitHeight(14);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                    setGraphic(null);
                } else {
                    setText(item);
                    setGraphic(folderIcon);  // 设置文件夹图标
                    getStyleClass().add("custom-tree-cell");
                }
            }
        });
    }
    //添加TreeView监听事件
    private void addTreeViewListener() {
        ViewHandler viewHandler = new ViewHandler(directoryTreeView, fileArea,fileContextMenu);
        viewHandler.addTreeViewListener();
    }

    // 添加新方法用于初始化显示C盘内容
    private void initRootContent() {
        // 设置初始路径为C盘
        ViewHandler.curentFilePath = "C盘\\";
        ViewHandler.filePath = "C盘\\";

        // 获取C盘下的文件列表
        List<String> files = DirectoryTreeBuilder.getFilesInDirectory("C盘\\");

        // 清空fileArea
        fileArea.getChildren().clear();

        // 显示文件列表
        for (String file : files) {
            BorderPane borderPane = new BorderPane();
            borderPane.getStylesheets().add(getClass().getResource("/nb/diskfilesystem/css/border.css").toExternalForm());
            borderPane.getStyleClass().add("borderpane");
            borderPane.setPrefSize(100, 100);

            // 设置边框处理器
            fileContextMenu.setBorderhandler(borderPane);

            Pane centerPane = new Pane();
            centerPane.getStyleClass().add("pane");

            // 根据文件类型设置不同的样式
            Directory_Node node = DirectoryTreeBuilder.getNodeByName("C盘\\", file);
            if (node != null && node.getAttribute() == 8) {
                centerPane.getStylesheets().add(getClass().getResource("/nb/diskfilesystem/css/folder.css").toExternalForm());
            } else {
                centerPane.getStylesheets().add(getClass().getResource("/nb/diskfilesystem/css/file.css").toExternalForm());
            }

            borderPane.setCenter(centerPane);

            // 修改这里：使用 ViewHandler 的 setBorderhandler 方法
            ViewHandler viewHandler = new ViewHandler(directoryTreeView, fileArea, fileContextMenu);
            viewHandler.setBorderhandler(borderPane);

            Label label = new Label(file);
            borderPane.setBottom(label);
            BorderPane.setAlignment(label, Pos.CENTER);

            fileArea.getChildren().add(borderPane);
        }
        // 更新路径显示
        TextField viewfilePath = (TextField) root.lookup("#viewfilePath");
        if (viewfilePath != null) {
            viewfilePath.setText("C盘\\");
        }
    }

    // 修改更新方法
    public void updateBlockView() {
        DiskVisualization.updateViews(blockVIew, circleView);
    }

    // 设置场景监听器
    private void setupSceneListener() {
        root.sceneProperty().addListener((obs, oldScene, newScene) -> {
            if (newScene != null) {
                newScene.setUserData(this);
            }
        });
    }


    @FXML
    private void handleFresh() {
        System.out.println("刷新当前fileArea区域");
        ViewHandler viewHandler = new ViewHandler(directoryTreeView, fileArea, fileContextMenu);
        viewHandler.updateFileArea(ViewHandler.filePath);

        // 更新路径显示
        TextField viewfilePath = (TextField) root.lookup("#viewfilePath");
        if (viewfilePath != null) {
            viewfilePath.setText(ViewHandler.filePath);
        }
    }

    @FXML
    private void handleLastFile() {
        System.out.println("返回上层目录");
        if (ViewHandler.filePath.equals("C盘\\")) {
            System.out.println("已经在根目录，无法返回上层目录");
            return;
        }
        // 将当前路径压入后退栈，用于后退操作
        backStack.push(ViewHandler.filePath);
        // 清空前进栈，因为开始了新的操作路径
        forwardStack.clear();

        // 获取父目录路径
        String parentPath = ViewHandler.filePath.substring(0,
                ViewHandler.filePath.lastIndexOf("\\", ViewHandler.filePath.length() - 2) + 1);

        // 更新当前路径
        ViewHandler.filePath = parentPath;
        ViewHandler.curentFilePath = parentPath;

        // 更新显示区域
        ViewHandler viewHandler = new ViewHandler(directoryTreeView, fileArea, fileContextMenu);
        viewHandler.updateFileArea(parentPath);

        // 更新路径显示
        TextField viewfilePath = (TextField) root.lookup("#viewfilePath");
        if (viewfilePath != null) {
            viewfilePath.setText(parentPath);
        }
    }

    @FXML
    private void handleBackFile() {
        System.out.println("返回上一个所在的目录");
        if (!backStack.isEmpty()) {
            // 将当前路径压入前进栈
            forwardStack.push(ViewHandler.filePath);

            // 从后退栈获取上一个路径
            String previousPath = backStack.pop();
            ViewHandler.filePath = previousPath;
            ViewHandler.curentFilePath = previousPath;

            // 更新显示区域
            ViewHandler viewHandler = new ViewHandler(directoryTreeView, fileArea, fileContextMenu);
            viewHandler.updateFileArea(previousPath);

            // 更新路径显示
            TextField viewfilePath = (TextField) root.lookup("#viewfilePath");
            if (viewfilePath != null) {
                viewfilePath.setText(previousPath);
            }
        } else {
            System.out.println("没有上一个目录");
        }
    }

    @FXML
    private void handleAdvanceFile() {
        System.out.println("返回点击backFile之前的文件目录");
        if (!forwardStack.isEmpty()) {
            // 将当前路径压入后退栈
            backStack.push(ViewHandler.filePath);

            // 从前进栈获取下一个路径
            String nextPath = forwardStack.pop();
            ViewHandler.filePath = nextPath;
            ViewHandler.curentFilePath = nextPath;

            // 更新显示区域
            ViewHandler viewHandler = new ViewHandler(directoryTreeView, fileArea, fileContextMenu);
            viewHandler.updateFileArea(nextPath);

            // 更新路径显示
            TextField viewfilePath = (TextField) root.lookup("#viewfilePath");
            if (viewfilePath != null) {
                viewfilePath.setText(nextPath);
            }
        } else {
            System.out.println("没有下一个目录");
        }
    }



}